package com.dubbo.protocol.netty;

import com.dubbo.protocol.bean.Invocation;
import com.dubbo.register.RegisterFactory;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;
import java.lang.reflect.Method;
import java.util.Map;

public class ServerHandler extends ChannelInboundHandlerAdapter
{
    //每个信息入站都会调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception
    {

        Invocation invocation = (Invocation) msg;


        //将消息记录到控制台
        System.out.println("httpHandler get invocation: " + invocation);

        Map<String, Object> localRegister = RegisterFactory.get(RegisterFactory.LOCAL);
        Class clazz = (Class) localRegister.get(invocation.getInterfaceName());

        Method method = clazz.getMethod(invocation.getMethodName(), invocation.getParamsClass());
        Object result = method.invoke(clazz.newInstance(), invocation.getParamsValue());

        ctx.write(result);  //将接受到的消息写给发送者
        ctx.flush();

    }

    //通知处理器最后的channelread是当前批处理中的最后一条信息调用
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception
    {
        //将未决消息冲刷到远程节点，并关闭该Channel
        ctx.writeAndFlush(Unpooled.EMPTY_BUFFER)
                .addListener(ChannelFutureListener.CLOSE);

        ctx.close(); //关闭该channel,如果做长连接，注释掉这行
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception
    {
        cause.printStackTrace();  //打印异常栈追踪
        ctx.close(); //关闭该channel
    }

}
